﻿using Avalonia.Controls.Notifications;
using Avalonia.Platform.Storage;
using Digitalmes.Core.Domain.Eitites;
using Digitalmes.Core.Services;
using Digitalmes.Infrastructure.IO;

namespace Digitalmes.AvaloniaUI.ViewModels;

public sealed partial class TurntableArchiveViewModel(IServiceProvider serviceProvider, ITurntableArchiveService turntableArchiveService) : ViewModelBase
{
    private WindowToastManager? _toastManager;

    // 查询--开始时间
    [ObservableProperty]
    public partial DateTime? StartDate { get; set; }

    // 查询--结束时间
    [ObservableProperty]
    public partial DateTime? EndDate { get; set; }

    // 分页--每页数量
    [ObservableProperty]
    public partial int PageSize { get; set; } = 50;

    // 分页--总数
    [ObservableProperty]
    public partial int TotalCount { get; set; }

    // 查询数据集合
    [ObservableProperty]
    public partial ObservableCollection<TurntableArchiveRecord> GridData { get; set; } = [];

    // 查询
    [RelayCommand]
    private async Task Query()
    {
        var (items, total) = await turntableArchiveService.GetPageListAsync(StartDate, EndDate, 1, PageSize);
        GridData = new(items);
        TotalCount = total;

        if (TotalCount == 0)
        {
            ShowToast("未找到数据");
        }
    }

    // 分页查询
    [RelayCommand]
    private async Task LoadPage(int? pageIndex)
    {
        int currentPage = pageIndex ?? 1;

        var (items, total) = await turntableArchiveService.GetPageListAsync(StartDate, EndDate, currentPage, PageSize);
        GridData = new(items);
        TotalCount = total;
    }

    // 导出数据
    [RelayCommand]
    private async Task Export(CancellationToken cancellationToken)
    {
        var sp = TopLevel?.StorageProvider;
        if (sp == null)
        {
            return;
        }

        var file = await sp.SaveFilePickerAsync(new FilePickerSaveOptions()
        {
            Title = "保存数据",
            SuggestedFileName = "转台存档数据",
            DefaultExtension = "xlsx",
            ShowOverwritePrompt = true,
        });
        if (file != null)
        {
            // 打开文件的写入流。
            await using var stream = await file.OpenWriteAsync();

            // 查询数据
            var data = await turntableArchiveService.GetListAsync(StartDate, EndDate, cancellationToken);

            // 写入数据
            var export = serviceProvider.GetRequiredService<IExcelExport>();
            await export.SaveAsAsync(stream, data, "数据", cancellationToken: cancellationToken);
        }
    }

    private void ShowToast(string message)
    {
        _toastManager ??= new(TopLevel) { MaxItems = 3 };
        _toastManager.Show(
                new Toast(message),
                showIcon: false,
                showClose: false,
                type: NotificationType.Warning,
                expiration: TimeSpan.FromSeconds(3),
                classes: ["Light"]);
    }
}
